<template>
  <div class="stock-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>药品库存管理</h2>
          <el-button type="primary" @click="openStockDialog()">新增库存</el-button>
        </div>
      </template>

      <el-table :data="stockList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="medicineId" label="药品ID"></el-table-column>
        <el-table-column prop="medicineName" label="药品名称"></el-table-column>
        <el-table-column prop="quantity" label="库存数量"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openStockDialog(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" size="small" @click="deleteStock(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      ></el-pagination>
    </el-card>

    <!-- 库存编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑库存' : '新增库存'" width="50%">
      <el-form :model="stockForm" label-width="100px">
        <el-form-item label="药品">
          <el-select v-model="stockForm.medicineId" placeholder="请选择药品">
            <el-option
              v-for="item in medicineOptions"
              :key="item.id"
              :label="item.medicineName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="库存数量">
          <el-input-number v-model="stockForm.quantity" :min="0"></el-input-number>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStock">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listStock, getStock, addStock, updateStock, delStock } from '@/api/stock'
import { listMedicine } from '@/api/medicine'

// 库存列表
const stockList = ref([])

// 药品选项
const medicineOptions = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框显示状态
const dialogVisible = ref(false)

// 是否为编辑模式
const isEdit = ref(false)

// 库存表单
const stockForm = reactive({
  id: null,
  medicineId: null,
  quantity: 0,
})

// 获取库存列表
const getStockList = async () => {
  try {
    const res = await listStock()

    // 获取药品列表
    const medicineRes = await listMedicine()
    const medicineMap = {}
    medicineRes.data.forEach((medicine) => {
      medicineMap[medicine.id] = medicine
    })

    // 合并药品信息
    stockList.value = res.data.map((stock) => {
      const medicine = medicineMap[stock.medicineId] || {}
      return {
        ...stock,
        medicineName: medicine.medicineName || '未知药品',
      }
    })

    total.value = res.total || 0
  } catch (error) {
    console.error('获取库存列表失败', error)
    ElMessage.error('获取库存列表失败')
  }
}

// 获取药品选项
const getMedicineOptions = async () => {
  try {
    const res = await listMedicine()
    medicineOptions.value = res.data || []
  } catch (error) {
    console.error('获取药品列表失败', error)
    ElMessage.error('获取药品列表失败')
  }
}

// 打开库存对话框
const openStockDialog = (stock) => {
  if (stock) {
    // 编辑模式
    isEdit.value = true
    Object.assign(stockForm, stock)
  } else {
    // 新增模式
    isEdit.value = false
    // 重置表单
    Object.assign(stockForm, {
      id: null,
      medicineId: null,
      quantity: 0,
    })
  }

  dialogVisible.value = true
}

// 保存库存
const saveStock = async () => {
  try {
    if (!stockForm.medicineId) {
      ElMessage.warning('请选择药品')
      return
    }

    if (isEdit.value) {
      // 编辑库存
      await updateStock(stockForm)
      ElMessage.success('库存更新成功')
    } else {
      // 新增库存
      await addStock(stockForm)
      ElMessage.success('库存添加成功')
    }

    // 关闭对话框
    dialogVisible.value = false

    // 刷新库存列表
    getStockList()
  } catch (error) {
    console.error('保存库存失败', error)
    ElMessage.error('保存库存失败')
  }
}

// 删除库存
const deleteStock = (stock) => {
  ElMessageBox.confirm(`确定要删除药品 ${stock.medicineName} 的库存记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await delStock(stock.id)
        ElMessage.success('库存删除成功')
        getStockList()
      } catch (error) {
        console.error('删除库存失败', error)
        ElMessage.error('删除库存失败')
      }
    })
    .catch(() => {})
}

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page
  getStockList()
}

// 初始化
onMounted(() => {
  getStockList()
  getMedicineOptions()
})
</script>
